using System.Collections.Generic;

namespace GameStateManagement.Input
{
    public enum ControlerPriority
    {
        Low,
        Medium,
        High
    };

    public class InputFsm : ICanHandleInput
    {
        private readonly List<PriorityHelper> _controlers;

        public InputFsm()
        {
            _controlers = new List<PriorityHelper>();
        }

        public void AddControler(InputBase controler, ControlerPriority priority)
        {
            _controlers.Add(new PriorityHelper(controler, priority));
            _controlers.Sort(new PriorityComparer());
        }



        public bool HandleInput(InputState state)
        {
            bool inputHandled = false;

            int k = 0;
            while (!inputHandled && k < _controlers.Count)
            {
                var controler = _controlers[k];
                inputHandled = controler.Controler.HandleInput(state);
                ++k;
            }

            return inputHandled;
        }

        private class PriorityHelper
        {
            public readonly InputBase Controler;
            public readonly ControlerPriority Priority;

            public PriorityHelper(InputBase controler, ControlerPriority priority)
            {
                Controler = controler;
                Priority = priority;
            }
        }

        private class PriorityComparer : IComparer<PriorityHelper>
        {
            #region Implementation of IComparer<PriorityHelper>

            public int Compare(PriorityHelper x, PriorityHelper y)
            {
                if (x.Priority > y.Priority)
                    return -1;

                return x.Priority < y.Priority ? 1 : 0;
            }

            #endregion
        }
    }
}
